package com.zb.mail;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/*
这里用到了多线程，因为发送邮件是需要时间去连接邮箱的服务器，若不使用多线程，则会卡在提交的网页中不断加载直至响应使用多线程可以异步处理，提高用户的体验度
*/
public class SendMail extends Thread {

    private String from = "发件人邮箱";
    private String username = "发件人用户名";
    private String password = "授权码";
    private String host = "smtp.qq.com";
    //QQ邮箱的主机协议
    private User user;
    public SendMail(User user) {
        this.user = user;
    }

    public void run() {
        Transport ts = null;
        try {
            Properties prop = new Properties();
            prop.setProperty("mail.host",host);
            prop.setProperty("mail.transport.protocol","smtp");
            prop.setProperty("mail.smtp.auth","true");
            //关于QQ邮箱 还要设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable","true");
            prop.put("mail.smtp.ssl.socketFactory",sf);
            //使用JavaMail发送邮件的5个步骤
            // 1.创建定义整个应用程序所需的环境信息的session对象
            Session session = Session.getDefaultInstance(prop, new Authenticator() {
                @Override protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username,password);
                }
            });
            session.setDebug(true);
            //开启debug模式 看到发送的运行状态
            // 2.通过session得到transport对象
            ts = session.getTransport();
            //3.使用邮箱的用户名和授权码连上邮件服务器
            ts.connect(host,username,password);
            //4.创建纯文本的简单邮件
            MimeMessage message = new MimeMessage(session);
            message.setSubject("只包含文本的普通邮件");
            //邮件主题
            message.setFrom(new InternetAddress(from));
            //发件人
            message.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getEmail()));
            //收件人
            String info = "注册成功!你的账号信息为: username = " + user.getName() + "password = " + user.getPassword();
            message.setContent("<h1 style='color: red'>" + info + "</h1>","text/html;charset=UTF-8");
            //邮件内容
            message.saveChanges();//保存设置
            // 5.发送邮件
            ts.sendMessage(message,message.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            try {
                ts.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }
}
